import axios from 'axios'
import Cookies from 'js-cookie'
import qs from 'qs'
import router from '@/router'
import nprogress from 'nprogress'
import store from '@/store'

//判断是开发环境还是生产环境
let host = "http://192.168.1.188:8080";
let baseURL = "";
if (process.env.NODE_ENV === "development") {
	baseURL = "http://192.168.1.188:8080/m.api";//开发环境
} else {
	baseURL = "http://81.71.14.65/";//生产环境
}
// 1.创建新的请求实例
const instance = axios.create({
	baseURL, //请求url
	timeout: 5000, //请求超时设置
	headers: {
		'content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
	}
});

// 拦截器
// 添加请求拦截器
instance.interceptors.request.use(config => {
	// 在发送请求之前做些什么--添加请求头--token
	nprogress.start();
	config.headers['AdminToken'] = Cookies.get("token");
	return config;
}, function (error) {
	// 对请求错误做些什么
	return Promise.reject(error);
});
const requestType = ["_mt=edit", "_mt=create", "_mt=delete"]
// 添加响应拦截器
instance.interceptors.response.use(async res => { //async异步
	// 对响应数据做点什么
	let data = res.data;
	let { errno, errmsg } = data;
	let path = router.currentRoute.value.fullPath;
	if (10006 === errno) {//令牌过期处理
		//获取接口请求的类型
		const configData = res.config.data;
		var index = -1;
		for (let i = 0; configData && i < requestType.length; i++) {//循环是否有requestType中定义的属性
			const typeName = requestType[i];
			index = configData.indexOf(typeName)
			if (index > -1) { //没有找到退出循环
				break
			}
		}
		if (-1 === index) {//没有的话重新获取登录令牌
			ElMessage.error(errmsg)
			router.replace({ path: "/login", query: { lo: path } });
			return
		} else {
			const { username, password } = store.state.userModule.userData;
			let loginData = { _gp: "admin", _mt: "login", username, password }
			let datas = await post(loginData) //await 等待一个异步方法执行完成
			let { errno, errmsg, data } = datas.data
			if (200 == errno) {
				Cookies.set("token", data)
			} else {
				ElMessage.error(errmsg)
				router.replace({ path: "/login", query: { lo: path } });
				return
			}
			nprogress.done()
			return instance.request(res.config) //错误抛出
		}
	}
	nprogress.done()
	return res;
}, function (error) {
	nprogress.done()
	// 对响应错误做点什么
	return Promise.reject(error);
});

function get(params) {
	return instance.get('', { params })
}

function post(data, params) {
	let datas = qs.stringify(data);
	return instance.post('', datas, { params })
}
function imgPost(url, data) {
	return instance.post(url, data);
}
export {
	get,
	post,
	host,
	imgPost
}
